const util = require('../../utils/util.js')
let p

Page({

	data: {
		signing: false,
		signed: false,
		signDuration: 0,
		nowDuration: 0,
		todaySignRecordList: [],
		yesterdaySignRecordList: [],
		logined: false,
		loadRecordFailed: false,
		loadingPanel: {
			tip: '构建中'
		},
		loadingBox: {
			show: false
		}
	},

	temp: {
		signUser: null,
		signId: null,
		signTime: null,
		durationTimer: null,
		scanTimer: null,
		signDeviceList: [],
		timeSpan: 0
	},

	onLoad: function (options) {
		p = this
		util.checkLogin({
			success: (userData) => {
				p.temp.signUser = userData.userId
				util.checkCommonData({
					success: (commonData) => {
						const { signDeviceList } = commonData
						p.temp.signDeviceList = signDeviceList
						p.checkSignStatus({
							success: (signInData) => {
								p.updateSignStatus(signInData)
								p.loadSignRecord()
								p.setData({
									logined: true
								})
								util.hideLoadingPanel(p)
							},
							fail: (code, msg) => {
								util.hideLoadingPanel(p)
								util.error('获取签到状态失败', util.errorHandler(code, msg) + '，下拉刷新重试')
							}
						})
					},
					fail: (code, msg) => {
						util.hideLoadingPanel(p)
						util.error('获取首页数据失败', '无法获取到首页数据哦，请检查网络稍后再试~')
					}
				})
			},
			fail: () => {
				util.hideLoadingPanel(p)
			}
		})
	},

	onUnload: function () {
		util.unloadPage('sign')
	},

	onShow: () => {
		if (util.globalData('logined')) {
			p.setData({
				logined: true
			})
			if (util.globalData('commonData')) {
				const { signDeviceList } = util.globalData('commonData')
				p.temp.signDeviceList = signDeviceList
			}
			if (p.data.signed)
				p.startDurationTimer()
			if (util.globalData('userData').userId != p.temp.signUser) {
				if (p.data.loadingPanel.tip)
					return
				util.showLoadingPanel(p, '构建中')
				p.checkSignStatus({
					success: (signInData) => {
						p.updateSignStatus(signInData)
						p.loadSignRecord()
						util.hideLoadingPanel(p)
					},
					fail: (code, msg) => {
						util.hideLoadingPanel(p)
						util.error('获取签到状态失败', util.errorHandler(code, msg) + '，下拉刷新重试')
					}
				})
			}
		}
		else {
			p.setData({
				nowDuration: 0,
				signDuration: 0,
				todaySignRecordList: [],
				yesterdaySignRecordList: [],
				signed: false,
				logined: false
			})
		}
	},

	onHide: () => {
		p.stopDurationTimer()
	},

	checkSignStatus: ({sync, success, fail}) => {
		util.request({
			source: 'sign',
			method: sync ? 'put' : 'get',
			uri: 'studio/sign/status',
			success,
			fail
		})
	},

	updateSignStatus: (signInData) => {
		const { signId, signUser, signTime, signDuration, serverTime } = signInData
		if (!signId) {
			p.stopDurationTimer()
			p.temp.signId = null
			p.temp.signUser = util.globalData('userData').userId
			p.temp.signTime = null
			p.setData({
				nowDuration: 0,
				signDuration: parseInt(signDuration),
				signing: false,
				signed: false
			})
			util.hideLoadingPanel(p)
			return
		}
		p.temp.signId = signId
		p.temp.signUser = signUser
		p.temp.signTime = signTime
		p.setData({
			signDuration: parseInt(signDuration),
			signing: false,
			signed: true
		})
		p.startDurationTimer(serverTime)
	},

	signIn: () => {
		if (p.data.signing)
			return
		p.setData({
			signing: true
		})
		p.checkDevices({
			success: (devices) => {
				console.log('找到签到基站', devices)
				util.request({
					source: 'sign',
					method: 'post',
					uri: 'studio/sign/in',
					data: {
						deviceId: devices[0].uuid.toLowerCase()
					},
					success: ({ signId, signTime, serverTime }) => {
						p.temp.signId = signId
						p.data.todaySignRecordList.unshift({
							signId,
							signStatus: 0,
							signTime
						})
						p.temp.signTime = signTime
						p.setData({
							signing: false,
							signed: true,
							todaySignRecordList: p.data.todaySignRecordList
						})
						p.startDurationTimer(serverTime)
					},
					fail: (code, msg) => {
						p.setData({
							signing: false
						})
						util.error('签到失败', util.errorHandler(code, msg))
					}
				})
			},
			fail: (code) => {
				p.setData({
					signing: false
				})
				switch(code) {
					case -1:
						util.error('签到失败', '您的手机似乎不支持部分蓝牙功能，无法完成签到，也许可以尝试重启蓝牙再试')
					break
					case -2:
						util.error('蓝牙未开启', '签到功能需要蓝牙支持，请打开蓝牙哦，如已经打开请重启蓝牙再试')
					break
					case -3:
						util.error('签到失败', '附近似乎未找到签到基站设备，如果签到基站就在附近请检查是否禁用了位置服务或微信使用位置服务的权限，如设置无问题请多次尝试签退')
					break
				}
			}
		})
	},

	signOut: () => {
		if (p.data.signing)
			return
		p.setData({
			signing: true
		})
		p.checkDevices({
			success: (devices) => {
				console.log('找到签退基站', devices)
				util.request({
					source: 'sign',
					method: 'post',
					uri: 'studio/sign/out',
					data: {
						signId: p.temp.signId,
						deviceId: devices[0].uuid.toLowerCase()
					},
					success: ({ signDuration, signTime }) => {
						p.stopDurationTimer()
						p.data.todaySignRecordList.unshift({
							signId: p.temp.signId,
							signStatus: 1,
							signDuration,
							signTime
						})
						p.setData({
							signing: false,
							signed: false,
							signDuration: p.data.signDuration + p.data.nowDuration,
							nowDuration: 0,
							todaySignRecordList: p.data.todaySignRecordList
						})
					},
					fail: (code, msg) => {
						p.setData({
							signing: false
						})
						util.error('签退失败', util.errorHandler(code, msg))
					}
				})
			},
			fail: (code) => {
				p.setData({
					signing: false
				})
				switch (code) {
					case -1:
						util.error('签退失败', '您的手机似乎不支持部分蓝牙功能，无法完成签退，也许可以尝试重启蓝牙再试')
						break
					case -2:
						util.error('蓝牙未开启', '签退功能需要蓝牙支持，请打开蓝牙哦，如已经打开请重启蓝牙再试')
						break
					case -3:
						util.error('签退失败', '附近似乎未找到签到基站设备，如果签到基站就在附近请检查是否禁用了位置服务或微信使用位置服务的权限，如设置无问题请多次尝试签退')
						break
				}
			}
		})
	},

	startDurationTimer: (serverTime) => {
		//计算服务器与客户端时间差
		if (serverTime)
			p.temp.timeSpan = util.timestamp() - serverTime
		console.log(p.temp.timeSpan)
		const nowDuration = (util.timestamp() - p.temp.timeSpan) - p.temp.signTime
		console.log(nowDuration, util.timestamp(), p.temp.signTime)
		p.setData({
			nowDuration: nowDuration > 0 ? nowDuration : 0
		})
		p.stopDurationTimer()
		p.temp.durationTimer = setInterval(() => {
			const _nowDuration = (util.timestamp() - p.temp.timeSpan) - p.temp.signTime
			p.setData({
				nowDuration: (_nowDuration > 0 ? _nowDuration : 0) + 1
			})
		}, 1000)
	},

	stopDurationTimer: () => {
		clearInterval(p.temp.durationTimer)
	},

	checkDevices({ success, fail, timeout }) {
		const signDeviceList = p.temp.signDeviceList
		console.log(signDeviceList)
		if (signDeviceList.length == 0) {
			util.error('无可用签到基站', '目前工作室无可用签到基站，可能是管理员正在更换基站，详情请联系工作室负责人解决')
			return
		}
		let deviceUUIDs = []
		for (let device of signDeviceList)
			deviceUUIDs.push(device.deviceId)
		wx.openBluetoothAdapter({
			success: (res) => {
				let devices = []
				wx.startBeaconDiscovery({
					uuids: deviceUUIDs,
					success: () => {
						console.log('start scan')
						wx.onBeaconUpdate(function (res) {
							if (res && res.beacons && res.beacons.length > 0) {
								devices = res.beacons
								wx.stopBeaconDiscovery()
								wx.closeBluetoothAdapter()
								console.log('stop scan')
								clearTimeout(p.temp.scanTimer)
								console.log(devices)
								success(devices)
							}
						})
						p.temp.scanTimer = setTimeout(() => {
							wx.stopBeaconDiscovery()
							wx.closeBluetoothAdapter()
							fail(-3)
						}, 10000)
					},
					fail: (err) => {
						console.error(err)
						wx.closeBluetoothAdapter()
						if(err.errCode == '1002')
							fail(-4)
						else
							fail(-1)
					}
				})
			},
			fail: (err) => {
				fail(-2)
			}
		})
		
	},

	goLogin: () => {
		wx.switchTab({
			url: '/pages/my/my',
		})
	},

	loadSignRecord: (obj) => {
		const { sync } = obj || {}
		if (p.data.loadRecordFailed)
			p.setData({
				loadRecordFailed: false
			})
		util.showLoadingBox(p)
		util.request({
			source: 'sign',
			method: sync ? 'put' : 'get',
			uri: 'studio/sign/record',
			success: ({ todaySignRecordList, yesterdaySignRecordList }) => {
				if(p.data.signed) {
					todaySignRecordList.unshift({
						signId: p.temp.signId,
						signStatus: 0,
						signTime: p.temp.signTime
					})
				}
				p.setData({
					todaySignRecordList,
					yesterdaySignRecordList
				})
				util.hideLoadingBox(p)
			},
			fail: (code, msg) => {
				console.error(code, msg)
				util.hideLoadingBox(p)
				p.setData({
					loadRecordFailed: true
				})
			}
		})
	},

	onPullDownRefresh: function () {
		wx.stopPullDownRefresh()
		if (!util.globalData('logined') || p.data.loadingPanel.tip)
			return
		util.showLoadingPanel(p, '构建中')
		p.checkSignStatus({
			success: (signInData) => {
				p.updateSignStatus(signInData)
				p.loadSignRecord({
					sync: true
				})
				util.hideLoadingPanel(p)
			},
			fail: (code, msg) => {
				util.hideLoadingPanel(p)
				util.error('获取签到状态失败', util.errorHandler(code, msg) + '，下拉刷新重试')
			}
		})
	},

	onShareAppMessage: function () {
		return {
			title: '微科创签到系统',
			path: '/pages/sign/sign'
		}
	}

})